const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcryptjs');
const path = require('path');

class Database {
    constructor() {
        this.db = new sqlite3.Database(path.join(__dirname, 'users.db'));
    }

    async init() {
        return new Promise((resolve, reject) => {
            this.db.serialize(async () => {
                try {
                    // 创建用户表
                    this.db.run(`
                        CREATE TABLE IF NOT EXISTS users (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            username TEXT UNIQUE NOT NULL,
                            password TEXT NOT NULL,
                            root_path TEXT NOT NULL
                        )
                    `);

                    // 检查是否已存在测试用户
                    this.db.get("SELECT * FROM users WHERE username = 'zs'", async (err, row) => {
                        if (!row) {
                            // 创建测试用户的根目录
                            const basePath = path.join(process.cwd(), 'storage');
                            const zsPath = path.join(basePath, 'zs');
                            const lsPath = path.join(basePath, 'ls');

                            // 生成加密密码
                            const salt = await bcrypt.genSalt(10);
                            const hashPwd = await bcrypt.hash('ddd', salt);
                            
                            // 插入测试用户
                            this.db.run(`
                                INSERT INTO users (username, password, root_path) 
                                VALUES ('zs', ?, ?), ('ls', ?, ?)
                            `, [hashPwd, zsPath, hashPwd, lsPath]);

                            // 确保用户目录存在
                            const fs = require('fs');
                            if (!fs.existsSync(basePath)) {
                                fs.mkdirSync(basePath);
                            }
                            if (!fs.existsSync(zsPath)) {
                                fs.mkdirSync(zsPath);
                            }
                            if (!fs.existsSync(lsPath)) {
                                fs.mkdirSync(lsPath);
                            }
                        }
                        resolve();
                    });
                } catch (error) {
                    reject(error);
                }
            });
        });
    }

    async validateUser(username, password) {
        return new Promise((resolve, reject) => {
            this.db.get(
                'SELECT * FROM users WHERE username = ?',
                [username],
                async (err, user) => {
                    if (err) {
                        reject(err);
                    } else if (!user) {
                        resolve(null);
                    } else {
                        const validPassword = await bcrypt.compare(password, user.password);
                        resolve(validPassword ? user : null);
                    }
                }
            );
        });
    }

    async getUserByUsername(username) {
        return new Promise((resolve, reject) => {
            this.db.get(
                'SELECT * FROM users WHERE username = ?',
                [username],
                (err, user) => {
                    if (err) reject(err);
                    else resolve(user);
                }
            );
        });
    }
}

module.exports = new Database();